import React, { PureComponent } from 'react'
import { Button, Form, Input, InputNumber, Select, Icon, Alert, notification, Transfer, LocaleProvider } from 'antd'
import zhCN from 'antd/lib/locale-provider/zh_CN'
import Modal from 'kenote-react-admin-modal'
import QueueAnim from 'rc-queue-anim'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { adminsGroupActions } from 'reduxs'
import _ from 'lodash'
import 'styles/modal.scss'

const FormItem = Form.Item
const Option = Select.Option
const TextArea = Input.TextArea
const typeName = {
  ['proto']: '线路',
  ['paths']: '渠道'
}

@connect(
  state => ({
    settPostPending : state.AdminsGroup.settPostPending,
    settPostError   : state.AdminsGroup.settPostError,
    settPostMessage : state.AdminsGroup.settPostMessage,
    listData        : state.AdminsGroup.listData,
    auth            : state.Passport.auth,
    paths           : state.AdminsGroup.paths,
    proto           : state.AdminsGroup.proto,
  }),
  dispatch => ({
    actions: bindActionCreators({...adminsGroupActions}, dispatch)
  })
)
export default class SettAdminsGroupModal extends PureComponent {

  state = {
    disabled: true,
    alert: null,
    mockData: [],
    targetKeys: [],
    initialize: false
  }

  constructor (props) {
    super(props)
    this._Modal = null
  }

  componentDidMount () {
    const { ModalOpts } = this.props
    this.props.actions.settGet(ModalOpts.type)
  }
  
  componentWillReceiveProps (nextProps) {
    const { settPostError, settPostMessage, ModalOpts } = nextProps
    if (settPostError > 0 && settPostMessage !== this.props.settPostMessage) {
      this.setState({ alert: (
        <Alert
          style={{ margin: '0 40px 24px' }}
          message={settPostMessage}
          type="error"
          showIcon
          key="aaa"
        />
      )})
    }
    if (settPostError === 0 && settPostMessage !== this.props.settPostMessage) {
      this._Modal.handleOnCancel()
      notification.info({
        message: `系统提示`,
        description: `用户组${typeName[ModalOpts.type]}配置更新成功！`,
        duration: 8,
        placement: 'bottomRight'
      })
    }
  }
  
  render () {
    const { visible, onCancel, settPostPending, auth, listData, ModalOpts, paths, proto } = this.props
    const { group } = auth
    const groupInfo = getGroupInfo(listData, ModalOpts.id)
    let setting = {}
    let selected = []
    switch (ModalOpts.type) {
      case 'paths':
        setting = paths
        selected = groupInfo.paths || []
        break
      case 'proto':
        setting = proto
        selected = groupInfo.proto || []
        break
      default:
        break
    }
    this.getMock(setting, selected)
    const options = {
      ref: view => this._Modal = view,
      visible: visible,
      onCancel: onCancel,
      title: `配置${typeName[ModalOpts.type]}权限 -- ${groupInfo.name}`,
      footer: [
        <Button
          onClick={() => this._Modal.handleOnCancel()}
          >
          取消
        </Button>,
        <Button
          type="primary"
          loading={settPostPending}
          onClick={this.handleSubmit}
          >
          确定
        </Button>
      ],
      width: 700,
      maskClosable: false
    }
    return (
      <Modal {...options}>
        <LocaleProvider locale={zhCN}>
          <div style={{ display: 'flex', justifyContent: 'center', padding: '15px 0' }}>
            {settPostPending ? null : (
              <QueueAnim component="div" type={['bottom', 'top']} leaveReverse>
                {this.state.alert ? this.state.alert : null}
              </QueueAnim>
            )}
            <Transfer
              dataSource={this.state.mockData}
              listStyle={{
                width: 300,
                height: 300
              }}
              targetKeys={this.state.targetKeys}
              onChange={this.handleChange}
              render={this.renderItem}
              />
          </div>
        </LocaleProvider>
      </Modal>
    )
  }

  getMock = (setting, selected = []) => {
    if (this.state.initialize || _.isEmpty(setting)) return
    const mockData = []
    for (let item of _.keys(setting).sort()) {
      let data = {
        key: item,
        title: item,
        description: setting[item],
      }
      mockData.push(data)
    }
    this.setState({ mockData, targetKeys: selected, initialize: true })
  }

  renderItem = (item) => {
    const customLabel = (
      <span className="custom-item" style={{ fontFamily: 'Comic Sans MS' }}>
        {item.title} - {item.description}
      </span>
    )
    return {
      label: customLabel, // for displayed item
      value: item.title, // for title and filter matching
    }
  }

  handleChange = (targetKeys, direction, moveKeys) => {
    this.setState({ targetKeys })
  }
  
  handleSubmit = () => {
    const { ModalOpts } = this.props
    this.props.actions.settPost(ModalOpts.type, ModalOpts.id, this.state.targetKeys)
  }
}

function getGroupInfo (listData, id) {
  return _.find(listData, { _id: id })
}